/***
 * 1、可以对原有原始进行编辑
 * 2、可以多无效鼠标响应
 * 3、可以删除选中的对象
 * 4、选中对象要高亮
 * 5、可以重置场景
 * 6、可以添加文字
 * 7、背景更换---
 * 8、大小重置---
 * 9、可以查看元素的位置，大小，内容
 *  10、编辑文字的字体，大小，颜色，位置，内容
 *
 *
 * */

class Meta{
    constructor(k, v) {
        this.key = k;
        this.name = v;
        this.status = 0;
    }

    draw(){
        if(this.status == 1){
            return '<li class="active" onclick="stage.selectMeta(\''+this.key+'\')">'+this.name+'</li>';
        }else{
            return '<li class="" onclick="stage.selectMeta(\''+this.key+'\')">'+this.name+'</li>';
        }
    }

    active(){
        this.status = 1;
    }

    inactive(){
        this.status = 0;
    }
}

class MetaObject{
    constructor(meta, x, y) {
        this.key = meta.key;
        this.name = meta.name;
        this.x = x;
        this.y = y;
        this.font = "隶书";
        this.fontSize = 20;
        this.color = "#000";

        this.status = 0;
    }

    draw(){
        if(this.status == 1){
            return '<li class="active" onclick="stage.selectObject(\''+this.key+'\')">'+this.name+'</li>';
        }else{
            return '<li class="" onclick="stage.selectObject(\''+this.key+'\')">'+this.name+'</li>';
        }
    }

    render(ctx){
        ctx.font = this.fontSize+"px "+this.font
        ctx.fillText(this.name, this.x, this.y)

        //
        let metrix = ctx.measureText(this.name)
        console.log('measure=', metrix)
    }

    move(x, y){
        this.x += x;
        this.y += y;
    }

    active(){
        this.status = 1;
    }

    inactive(){
        this.status = 0;
    }
}

class MetaManager{
    constructor(stage) {
        this.stage = stage
        this.metaList = [];
        this.selectIndex = -1;
    }

    /**
     * 添加元素
     * */
    add(key, name){
        this.metaList.push(new Meta(key, name))
    }

    render(metaListDiv){
        let metaHtml = "";
        this.metaList.forEach((meta)=>{
            metaHtml += meta.draw()
        })
        metaListDiv.innerHTML = metaHtml;
    }

    //选中模型
    selectMeta(key){
        this.clearSelect()
        for(var index = 0; index < this.metaList.length; index++){
            if(this.metaList[index].key == key){
                this.metaList[index].active();
                this.selectIndex = index;
                return true;
            }
        }
        return false;
    }

    clearSelect(){
        this.selectIndex = -1;
        this.metaList.forEach( (meta) => {
            meta.inactive()
        })
    }
}

class ObjectManager{
    constructor(stage) {
        this.stage = stage
        this.objectList = [];
        this.selectIndex = -1;
    }

    add(meta, x, y){
        this.objectList.push(new MetaObject(meta, x,y))
    }

    remove(){
        this.objectList.splice(this.selectIndex, 1)
        this.selectIndex = -1;
    }

    update(){}

    /**
     * 移动坐标元素
     * */
    move(deltaX,deltaY){
        if(this.selectIndex == -1 || this.objectList.length < this.selectIndex){
            return;
        }

        this.objectList[this.selectIndex].move(deltaX, deltaY)
    }


    renderDiv(objectDiv){
        let objectHtml = "";
        this.objectList.forEach((obj)=>{
             objectHtml += obj.draw()
        })
        objectDiv.innerHTML = objectHtml;
    }

    render(ctx){
        this.objectList.forEach((obj)=>{
            obj.render(ctx)
        })
    }


    selectObject(key){
        this.clearSelect()
        for(var index = 0; index < this.objectList.length; index++){
            if(this.objectList[index].key == key){
                this.objectList[index].active();
                this.selectIndex = index;
                return true;
            }
        }
        return false;
    }

    clearSelect(){
        this.selectIndex = -1;
        this.objectList.forEach( (item) => {
            item.inactive()
        })
    }
}

class Background{
    constructor(uri, w, h) {
        this.width = w;
        this.height = h;

        this.image = new Image(w, h);
        this.image.src = uri;
        // this.image.onload =  () =>{
        //     this.imageLoad()
        // }
    }

    imageLoad( cl ){
        if (cl){
            cl();
        }
    }

    render(ctx){
        ctx.drawImage(this.image, 0, 0, this.width, this.height)
    }
}


class Stage{
    /**
     * status 0 浏览模式  1 编辑模式
     * */
    constructor(objectListId, metaListId, canvasId, uri, w, h) {
        this.status = 0;
        this.mode = 0;//0-普通模式  1-移动模式
        this.canvas = document.getElementById(canvasId);
        this.ctx = this.canvas.getContext('2d');
        this.canvas.width = w;
        this.canvas.height = h;
        this.canvas.style.width= this.canvas.width+"px"
        this.canvas.style.height=this.canvas.height+"px"
        this.objectManager = new ObjectManager(this)
        this.metaManager = new MetaManager(this)
        this.background = new Background(uri, w, h);

        this.metaListDiv = document.getElementById(metaListId);
        this.objectListDiv = document.getElementById(objectListId);

        this.initForm()

        this.canvas.onclick = (e) => {
            if(this.mode == 0){
                this.input(e)
            }
        }

        this.canvas.onmousedown = (e)=>{
            this.mouseHandle(e, "down")
        }

        this.canvas.onmousemove = (e) => {
            this.mouseHandle(e, 'move')
        }

        this.canvas.onmouseup = (e) => {
            this.mouseHandle(e, 'up')
        }
    }

    changeStatus(st){
        this.status = st;
        if(this.status == 0){
            this.metaManager.clearSelect()
            this.objectManager.clearSelect()
        }
    }

    render(){
        //绘制背景
        this.background.render(this.ctx)
        //绘制meta
        this.metaManager.render(this.metaListDiv)

        //objectDiv
        this.objectManager.renderDiv(this.objectListDiv)

        //内部绘制
        this.objectManager.render(this.ctx)
    }

    updateRender(){
        //绘制背景
        this.background.render(this.ctx)
        //内部绘制
        this.objectManager.render(this.ctx)
    }

    reset(){

    }

    getData(){
        let result = {
            background:{
                uri:this.background.image.src,
                width:this.canvas.width,
                height:this.canvas.height
            },
            objectList:this.objectManager.objectList,
            metaList:this.metaManager.metaList
        };
        /**
        this.objectManager.objectList.forEach( (item, index) => {
        })
        this.metaManager.metaList.forEach( (item, index) => {
        });*/

        return JSON.stringify(result);
    }

    parseData(json){
        let result = JSON.parse(json);
        //重置场景
        let w = result.background.width
        let h = result.background.height
        this.background = new Background(result.background.uri, result.background.width, result.background.height);
        this.background.image.onload = ()=>{
            this.canvas.width = w;
            this.canvas.height = h;
            this.canvas.style.width= this.canvas.width+"px"
            this.canvas.style.height=this.canvas.height+"px"
        }

        //meta相关
        this.metaManager.metaList = [];
        result.metaList.forEach((meta)=>{
            this.metaManager.metaList.push( new Meta(meta.key, meta.name) );
        })

        this.objectManager.objectList =[];
        result.objectList.forEach((obj)=>{
            //this.objectManager.objectList.push(new MetaObject());
        })

        setTimeout(()=>{
            this.render()
        }, 1000)
    }

    input(event){
        console.log(event)
        let posX = event.x - 200;
        let posY = event.y;

        //功能菜单不处理
        if(posX < 0){
            return;
        }
        if(posX > this.background.width || posY > this.background.height){
            return;
        }
        console.log("1111")

        //浏览模式不处理
        if (this.status == 0){
            return;
        }

        //编辑模式查看
        if (this.metaManager.selectIndex > -1){
            let meta = this.metaManager.metaList[this.metaManager.selectIndex];
            this.objectManager.add(meta, posX,posY);
            this.render()
        }else if (this.objectManager.selectIndex > -1){

        }
    }

    mouseHandle(e, type){
        if (type == "down"){
            this.mode = 1;
            this.startX = e.x;
            this.startY =e.y;
        }else if (type == "move" && this.mode == 1){
            this.objectManager.move(e.x-this.startX, e.y-this.startY);
            this.startX = e.x;
            this.startY =e.y;
            this.updateRender()
        }else {
            this.mode = 0;
        }
    }

    selectMeta(event){
        if(this.status == 0){
            return;
        }
        this.objectManager.clearSelect()
        this.metaManager.selectMeta(event);
        this.render()
    }

    selectObject(event){
        if(this.status == 0){
            return;
        }
        this.metaManager.clearSelect()
        this.objectManager.selectObject(event);
        this.render()
    }

    remove(){
        if (this.objectManager.selectIndex > -1){
            //删除选中的元素
            this.objectManager.remove()
            this.render()
        }
    }

    attrView(){
        let el = document.getElementById("tip");
        el.style.display = "block";

        //选择相关数值
        if(this.objectManager.selectIndex > -1){
           let obj = this.objectManager.objectList[this.objectManager.selectIndex];
            document.getElementById("fontSize").value = obj.fontSize;
            document.getElementById("font").value =  obj.font;
        }
    }


    initForm(){
        let html =
            `<div id="tip" style="display: none; position: absolute; top:100px;left: 200px;background: #f0f0f0;padding: 20px;">
                <div style="display: flex;flex-direction: column">
                    <div>大小:
                        <input id="fontSize" value="">
                    </div>
                    <div>字体:
                        <select id="font">
                            <option value="隶书">隶书</option>
                            <option value="宋体">宋体</option>
                        </select>
                    </div>
                    <div>
                        <button onclick="stage.cancelForm()">取消</button>
                        <button onclick="stage.confirmForm()">确定</button>
                    </div>
                </div>
            </div>`;
        window.document.write(html);
    }

    cancelForm(){
        let el = document.getElementById("tip");
        el.style.display = "none"
    }

    confirmForm(){
        this.cancelForm()
        if(this.objectManager.selectIndex > -1){
            let obj = this.objectManager.objectList[this.objectManager.selectIndex];
            obj.fontSize = document.getElementById("fontSize").value;
            obj.font = document.getElementById("font").value;
            this.render()
        }
    }
}